<template>
  <div class="app-container">

    <el-form
      v-show="showSearch"
      ref="queryForm"
      :model="queryParams"
      :inline="true"
    >

      <el-form-item :label="$t('alarm.alarmType')" prop="alarmType">
        <el-select
          v-model="queryParams.param.alarmType"
          :placeholder="$t('operating.pleaseChosen')"
          style="width: 120px"
        >
          <el-option
            v-for="item in alarmTypes"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item :label="$t('alarm.alarmStatus')" prop="state">
        <el-select
          v-model="queryParams.param.state"
          filterable
          :placeholder="$t('operating.pleaseChosen')"
          style="width: 100px"
        >
          <el-option
            v-for="item in alarmStatusArray"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item :label="$t('celler.interTime')">
        <el-date-picker
          v-model="dateRange"
          size="small"
          style="width: 240px"
          value-format="yyyy-MM-dd HH:mm:ss"
          type="datetimerange"
          range-separator="-"
          :start-placeholder="$t('common.cstartTime')"
          :end-placeholder="$t('common.cendTime')"
        />
      </el-form-item>

      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="searchData"
        >{{ $t("common.csearch") }}</el-button>
        <!-- <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">{{
          $t("common.creset")
        }}</el-button> -->
      </el-form-item>
    </el-form>

    <!-- 访客操作 -->
    <el-row :gutter="10" class="mb8" style="display: flex; align-items: center">
      <!-- <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="addCellerInfo"
        >{{ $t('common.caddkey') }}</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="leadingOutData"
        >{{ $t("operating.export") }}</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
        >{{ $t("operating.import") }}</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleMultiConfirm"
        >{{ $t("operating.BatchConfirmation") }}</el-button>
      </el-col>
      <!-- @click="handleDelete" -->

      <right-toolbar
        :show-search.sync="showSearch"
        :columns="columns"
        @queryTable="initAlarmlist"
      />
    </el-row>
    <!--
    <export-file
      :is-show="editExportVisible"
      :add-path="'/resource/importAppend'"
      :cover-path="'/resource/importReplace'"
      @changeShow="updateList($event)"
    /> -->

    <el-main>
      <!--表格-->
      <el-table
        ref="multipleTable"
        class="datalist"
        :data="tableData"
        :max-height="tableMaxHeight"
        :row-class-name="tableRowClassName"
        @selection-change="handleChange"
      >
        <el-table-column type="selection" width="50" />
        <el-table-column
          v-if="columns[0].visible"
          key="alarmType"
          prop="alarmType"
          :label="$t('alarm.alarmType')"
          min-width="80"
        />
        <!-- 告警地点 -->
        <el-table-column
          v-if="columns[1].visible"
          prop="fenceName"
          :label="$t('alarm.AlarmLocation')"
          min-width="80"
        />
        <!-- 告警对象 -->
        <el-table-column
          v-if="columns[2].visible"
          prop="resourceName"
          :label="$t('alarm.AlarmObject')"
          min-width="80"
        />
        <!-- 开始时间 -->
        <el-table-column
          v-if="columns[3].visible"
          prop="intime"
          :label="$t('operating.StartTime')"
          min-width="120"
        />
        <!-- 结束时间 -->
        <el-table-column
          v-if="columns[4].visible"
          prop="outTime"
          :label="$t('operating.EndTime')"
          min-width="120"
        />
        <el-table-column
          v-if="columns[5].visible"
          prop="status"
          :label="$t('alarm.alarmStatus')"
          min-width="100"
        />

        <el-table-column :label="$t('operating.operating')" min-width="150">
          <template slot-scope="scope">
            <el-tooltip
              :content="$t('alarm.ConfirmationAlarm')"
              placement="top"
            >

              <el-button
                style="font-size:20px"
                class="table-scope-button"
                size="mini"
                type="text"
                :icon="scope.row.status == '已处理' ? 'iconfont iconright':'iconfont iconbig'"
                :disabled="scope.row.status == '已处理' ? true : false"
                @click="handleConfirm(scope.$index, scope.row)"
              />
            </el-tooltip>
            <!--超时，已处理，未处理
            <el-tooltip
              :content="$t('alarm.MonitoringSnapshot')"
              placement="top"
            >
              <el-button
                class="table-scope-button"
                size="mini"
                type="text"
                icon="al-icon-carzhaopian-copy"
                :disabled="scope.row.snapUrlList === undefined ? true : false"
                @click="handlePicture(scope.$index, scope.row)"
              />
            </el-tooltip> -->

            <!-- 新增视频mp4视频播放功能 -->
            <!-- <el-tooltip :content="$t('alarm.VidePlayMp4')" placement="top">
              <el-button
                class="table-scope-button"
                style="font-size: 20px"
                type="text"
                icon="el-icon-video-camera-solid"
                :disabled="scope.row.recordUrlList === undefined ? true : false"
                @click="handleVideoMp4(scope.$index, scope.row)"
              />
            </el-tooltip> -->

            <el-tooltip
              :content="$t('alarm.OneMinuteBeforeAndAfter')"
              placement="top"
            >
              <el-button
                class="table-scope-button"
                size="mini"
                type="text"
                icon="al-icon-carlishiguiji1-copy"
                @click="historicalTrackPlayBack(scope.$index, scope.row)"
              />
            </el-tooltip>
            <el-tooltip :content="$t('alarm.alarmLocation')" placement="top">
              <el-button
                class="table-scope-button"
                size="mini"
                type="text"
                icon="al-icon-carshishiweizhi-copy"
                :disabled="scope.row.alarmType === 'SOS告警' ? false : true"
                @click="handlePosition(scope.$index, scope.row)"
              />
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="initAlarmlist"
      />

      <!-- 照片查看器 -->
      <el-dialog
        :visible.sync="pictureDialogVisible"
        width="50%"
        style="text-align: center"
        :close-on-click-modal="false"
      >
        <el-carousel height="450px" :loop="true" :autoplay="false">
          <el-carousel-item v-for="(item, index) in photoPaths" :key="index">
            <h3 style="margin-bottom: 20px">{{ item.name }}</h3>
            <img :src="item.path" style="height: 400px">
          </el-carousel-item>
        </el-carousel>
      </el-dialog>
    </el-main>

    <!-- 短视频回放查看器 -->
    <el-dialog
      id="videoPlace"
      :visible.sync="videoDialogVisible"
      width="50%"
      style="text-align: center; margin-top: 200px"
      :destroy-on-close="true"
      @close="closeDialog2"
    />

    <!-- 地图模块 -->
    <el-dialog
      :visible.sync="positionDialogVisible"
      width="50%"
      @open="openPosiotionDialogCallBack"
      @close="closePositionDialogCallBack"
    >
      <div id="map" style="width: 100%; height: 500px" />
    </el-dialog>

    <!-- 新增轨迹回放功能 -->
    <el-dialog
      :title="$t('history.showDetail')"
      :visible.sync="showDetail"
      width="80%"
      :close-on-click-modal="false"
      custom-class="history-detial"
      @open="openDialogCallBack"
      @close="closeDialog"
    >
      <div id="mapbox3" style="height: 700px; width: 100%">
        <!-- 地图容器 -->
        <!-- <div id="map" v-bind:style="{height: mapHeight, width: mapWidth}"></div> -->
        <div id="map" style="height: 700px; width: 100%" />

        <div class="positiondiv"><span /></div>
        <div class="scalediv"><span /></div>
        <!-- 弹出气泡 -->
        <!-- <div style="display: none;">
          <div id="popup" class="ol-popup">
            <a href="javascript:;" id="popup-closer" class="ol-popup-closer" title="关闭"></a>
            <div id="popup-content"></div>
          </div>
        </div> -->

        <!-- 显示当前点时间 -->
        <div class="historytime">
          {{ $t("history.historytime") }}<span id="Tagtime" />
        </div>
        <el-row class="toolrow" :gutter="20">
          <el-col :span="2">
            <!-- 播放暂定按钮 -->
            <el-tooltip :content="playbtnTooltip" placement="top">
              <el-button
                ref="playbtn"
                class="playbtn"
                type="primary"
                icon="al-icon-carplay"
                size="mini"
                circle
                @click="clickPlayBtn"
              />
            </el-tooltip>
          </el-col>
          <el-col :span="16">
            <!-- 进度滑块 -->
            <div class="progress_slider">
              <el-slider
                v-model="progressIndex"
                :max="progressMax"
                :format-tooltip="formatProgressTooltip"
                @change="progressValueChange"
              />
            </div>
          </el-col>
          <el-col :span="6">
            <!-- 速度滑块 -->
            <div class="speed_slider">
              <span>{{ $t("history.speed") }}</span>
              <el-select v-model="speedIndex" style="width: 80px">
                <el-option
                  v-for="item in speedIndexs"
                  :key="item.speed"
                  :label="item.label"
                  :value="item.speed"
                />
              </el-select>
            </div>
          </el-col>
        </el-row>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { baseUrl } from '@/utils/global.js'
import {
  getListData,
  confirmAlarm,
  getMap,
  getHistoryInfoDetail,
  downloadFile
} from '@/api/cy.js'
import Cookie from 'js-cookie'
import {
  Load_Map,
  TagStyle,
  _TransMetric,
  _TransPixel,
  _dPR,
  _iMap,
  t,
  setMapCenter,
  FenceLayer,
  FenceSource,
  LoadTypeData,
  sendThis
} from '@/utils/iMap.js'
import $ from 'jquery'
import { Vector as VectorLayer } from 'ol/layer.js'
import { Vector } from 'ol/source.js'
import { Circle, LineString, Point, Polygon } from 'ol/geom.js'
import Feature from 'ol/Feature.js'
import { Fill, Stroke, Style, Text, Icon } from 'ol/style.js'

export default {
  data() {
    return {
      rules: {},
      multiple: true,
      total: 0, // 总页数
      dateRange: [], // 来访日期范围
      tableData: [], // 访客表格数据
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        param: {
          alarmType: undefined,
          state: undefined
        }
      },
      editExportVisible: false, // 导入弹窗
      showSearch: true, // 是否显示条件查询
      // 设置表格行列是否显示
      columns: [
        { key: 0, label: this.$i18n.t('alarm.alarmType'), visible: true },
        { key: 1, label: this.$i18n.t('alarm.AlarmLocation'), visible: true },
        { key: 2, label: this.$i18n.t('alarm.AlarmObject'), visible: true },
        { key: 3, label: this.$i18n.t('operating.StartTime'), visible: true },
        { key: 4, label: this.$i18n.t('operating.EndTime'), visible: true },
        { key: 5, label: this.$i18n.t('alarm.alarmStatus'), visible: true }
      ],

      alarmTypeValue: '', // 选择的告警类型值
      alarmStatusValue: '', // 选择的告警状态
      multipleSelection: [],
      tableDataNum: 0, // 表格数据的数量
      cur_page: 1, // 当前显示页
      size_page: 10, // 每页显示数据条数
      dateValue: '', // 日期控件值
      pictureDialogVisible: false, // 显示抓拍快照
      positionDialogVisible: false, // 显示告警位置的地图控件
      mapId: 0, // 存储触发SOS告警的图层ID
      rowData: null,
      alarmSource: null,
      alarmLayer: null,
      photoPaths: [], // 存储图片路径
      alarmTypes: [
        { value: '', label: this.$t('alarm.alarmTypes.all') },
        { value: 'alarmIn', label: this.$t('alarm.alarmTypes.illegalEntry') },
        {
          value: 'alarmOut',
          label: this.$t('alarm.alarmTypes.illegalDeparture')
        },
        { value: 'SOS', label: this.$t('alarm.alarmTypes.sosAlarm') },
        { value: 'timeOut', label: this.$t('alarm.alarmTypes.timeoutAlarm') },
        { value: 'gatherOver', label: this.$t('alarm.alarmTypes.overAlert') },
        { value: 'freeFal', label: this.$t('alarm.alarmTypes.fallWarning') },
        {
          value: 'strapBroken',
          label: this.$t('alarm.alarmTypes.wristBandBreak')
        },
        {
          value: 'unHelmet',
          label: this.$t('alarm.alarmTypes.notWearingAHelmet')
        },
        {
          value: 'unWorkClothes',
          label: this.$t('alarm.alarmTypes.notWearingOveralls')
        },
        {
          value: 'lowBattery',
          label: this.$t('alarm.alarmTypes.lowBatteryAlarm')
        },
        {
          value: 'lackOfStaff',
          label: this.$t('alarm.alarmTypes.missingAlarm')
        },
        { value: 'static', label: this.$t('alarm.alarmTypes.stationaryAlarm') },
        { value: 'stay', label: this.$t('alarm.alarmTypes.retentionAlarm') },
        {
          value: 'heartRateAlarm',
          label: this.$t('alarm.alarmTypes.heartRateAlarm')
        }
      ],

      alarmStatusArray: this.$t('alarm.alarmStatusArray'),

      tableMaxHeight: 630,
      initB: false, // 判断是否点击过搜索按钮
      param: {}, // 请示历史轨迹是的参数
      showDetail: false, // 显示详情
      timeoutIndex: null,
      playbtnTooltip: '暂停',
      progressIndex: 0, // 播放进度位置
      progressLimitIndex: 0,
      lineSource: null, // 标签资源容器
      trackData: [],
      progressMax: 0, // 播放进度最大值
      speedIndex: 2,
      speedIndexs: [
        { speed: 1, label: 'x1' },
        { speed: 2, label: 'x2' },
        { speed: 4, label: 'x4' },
        { speed: 8, label: 'x8' },
        { speed: 16, label: 'x16' }
      ],
      currentMapId: null,
      styles: {
        linestring: new Style({
          stroke: new Stroke({
            color: 'green',
            width: 3
          }),
          zIndex: 999
        }),
        geoMarker: new Style({
          image: new Icon({
            offset: [0, 0],
            size: [22, 30],
            // src: "../../static/img/icon/5ren.png",
            src: require('../../../assets/images/5ren.png'),
            color: '#8959A8',
            opacity: 1
          }),
          zIndex: 10000
        }),
        point: new Style({
          image: new Circle({
            radius: 5,
            snapToPixel: false,
            fill: new Fill({
              color: 'red'
            }),
            stroke: new Stroke({
              color: 'white',
              width: 1
            })
          })
        })
      },
      videoDialogVisible: false
    }
  },

  //  已经完成模板渲染或者el对应的html渲染后
  mounted() {
    this.setQueryTime()
    this.initAlarmlist()
    this.windowRefresh()
    const self = this
    window.onresize = function temp() {
      self.windowRefresh()
    }
  },

  methods: {
    /*
    导出表格中的内容
     */
    leadingOutData() {
      // 根据搜索条件导出内容
      const urlPath = '/report/reportAlarm?token=' + (this.queryParams.param.alarmType === '' ? '' : ('alarmType=' + this.queryParams.param.alarmType)) +
        (this.queryParams.param.state === '' ? '' : ('&state=' + this.queryParams.param.state)) +
        '&startTime=' + this.dateRange[0] + '&endTime=' + this.dateRange[1] + '&token=' + Cookie.get('token')
      const filename = 'alarmlist_' + new Date().getTime() + '.xls'
      downloadFile(urlPath, filename)
    },

    /** 导出按钮操作 */
    handleExport() {
      this.editExportVisible = true
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.initAlarmlist()
    },

    /** 重置搜索操作 */
    resetQuery() {
      this.dateRange = []
      this.queryParams.param.alarmType = undefined
      this.queryParams.param.state = undefined
      this.resetForm('queryForm')
      this.handleQuery()
    },

    // 设置查询时间
    setQueryTime() {
      const myDate = new Date()
      const year = myDate.getFullYear()
      const month = myDate.getMonth()
      const day = myDate.getDate()
      this.dateValue = [
        new Date(year, month, day, '08', '00', '00'),
        new Date(year, month, day, '18', '00', '00')
      ]
    },
    initAlarmlist() {
      if (this.dateRange.length > 0) {
        this.queryParams.param.startTime = this.dateRange[0]
        this.queryParams.param.endTime = this.dateRange[1]
      } else {
        delete this.queryParams.param.startTime
        delete this.queryParams.param.endTime
      }

      getListData(this.queryParams).then((res) => {
        if (res.code === 200) {
          if (res.data.content.length > 0) {
            this.total = res.data.totalSize
            this.tableData = res.data.content
          } else {
            this.msgError(this.$t('Notice.noDataHasBeenFound'))
          }
        }
      })
    },

    /**
     * 确认
     */
    handleConfirm(index, row) {
      const param = []
      const obj = {
        idx: row.idx,
        uuid: row.uuid,
        intime: row.intime,
        alarmType: row.alarmType,
        resourceId: row.resourceId
      }
      if (row.layerName) {
        obj['layerName'] = row.layerName
      }
      if (row.layerId) {
        obj['layerId'] = row.layerId
      }
      param.push(obj)
      this.handleConfirmAlarm(param)
    },
    /**
     * 确认告警
     */
    handleConfirmAlarm(param) {
      confirmAlarm(param).then((res) => {
        /** debug cao res总是为null，但是实际请求已经成功*/
        if (res.code === 200) {
          this.msgSuccess(res.msg)
          this.initAlarmlist()
          // setTimeout(() => {
          //   this.initAlarmlist()
          // }, 1500)
        } else {
          this.msgError(res.msg)
        }
      })
    },

    /**
     * 根据表格中内容切换颜色
     */
    tableRowClassName(row, index) {
      // 告警类型判断
      switch (row.row.alarmType) {
        case 'alarmIn':
          row.row.alarmType = this.$t('alarm.alarmTypes.illegalEntry')
          break
        case 'alarmOut':
          row.row.alarmType = this.$t('alarm.alarmTypes.illegalDeparture')
          break
        case 'SOS':
          row.row.alarmType = this.$t('alarm.alarmTypes.sosAlarm')
          break
        case 'timeOut':
          row.row.alarmType = this.$t('alarm.alarmTypes.timeoutAlarm')
          break
        case 'gatherOver':
          row.row.alarmType = this.$t('alarm.alarmTypes.overAlert')
          break
        case 'freeFal':
          row.row.alarmType = this.$t('alarm.alarmTypes.fallWarning')
          break
        case 'unHelmet':
          row.row.alarmType = this.$t('alarm.alarmTypes.notWearingAHelmet')
          break
        case 'unWorkClothes':
          row.row.alarmType = this.$t('alarm.alarmTypes.notWearingOveralls')
          break
        case 'strapBroken':
          row.row.alarmType = this.$t('alarm.alarmTypes.wristBandBreak')
          break
        case 'lackOfStaff':
          row.row.alarmType = this.$t('alarm.alarmTypes.missingAlarm')
          break
        case 'lowBattery':
          row.row.alarmType = this.$t('alarm.alarmTypes.lowBatteryAlarm')
          break
        case 'static':
          row.row.alarmType = this.$t('alarm.alarmTypes.stationaryAlarm')
          break
        case 'stay':
          row.row.alarmType = this.$t('alarm.alarmTypes.retentionAlarm')
          break
        case 'heartRateAlarm':
          row.row.alarmType = this.$t('alarm.alarmTypes.heartRateAlarm')
          break
        default:
          break
      }

      // 状态判断
      if (row.row.status === '已处理' || row.row.status === '已處理') {
        // 已处理
        return 'background-green'
      } else {
        if (row.row.alarmType === 'SOS') {
          // 未处理
          return 'background-red'
        } else {
          return 'background-pink'
        }
      }
    },

    /**
     * 批量确认
     */
    handleMultiConfirm() {
      this.tableDataNum = 0
      this.tableData = []
      const param = []
      for (let i = 0; i < this.multipleSelection.length; i++) {
        if (
          this.multipleSelection[i].status == this.$t('alarm.unprocessedAlarm')
        ) {
          const obj = {
            idx: this.multipleSelection[i].idx,
            uuid: this.multipleSelection[i].uuid,
            intime: this.multipleSelection[i].intime,
            alarmType: this.multipleSelection[i].alarmType,
            resourceId: this.multipleSelection[i].resourceId
          }
          if (this.multipleSelection[i].layerName) {
            obj['layerName'] = this.multipleSelection[i].layerName
          }
          if (this.multipleSelection[i].layerId) {
            obj['layerId'] = this.multipleSelection[i].layerId
          }
          param.push(obj)
        }
      }
      console.log(this.multipleSelection, this.$t('alarm.unprocessedAlarm'), param)
      if (param.length > 0) {
        this.handleConfirmAlarm(param)
      } else {
        this.msgInfo()
      }
    },

    /**
     * 显示图片
     */
    handlePicture(index, row) {
      this.pictureDialogVisible = true
      this.photoPaths = []
      if (typeof row.snapUrlList !== 'undefined') {
        const json = $.parseJSON(row.snapUrlList)
        let name
        let path
        for (let i = 0; i < json.length; i++) {
          name =
            row.resourceName +
            '_' +
            row.alarmType +
            '_' +
            json[i].fenceName +
            '_' +
            json[i].cameraName +
            '_' +
            json[i].snapTime
          path = baseUrl + json[i].snapUrl
          const obj = { name: name, path: path }
          this.photoPaths.push(obj)
        }
      } else {
        this.v_MyMessage(this.$t('alarm.alarmWarning.noImage'), 'warning')
      }
    },
    /**
     * 显示历史轨迹
     */
    handleHistory(index, row) {
      if (row.intime != undefined && row.outTime != undefined) {
        const intime = this.v_FormatDateTime(
          new Date(row.intime).getTime() - 1000 * 60
        )
        const outtime = this.v_FormatDateTime(
          new Date(row.outTime).getTime() + 1000 * 60
        )

        this.$router.push({
          path: '/HistoryDisplayInfo',
          query: {
            source: 'AlarmRecord',
            starttime: intime,
            endtime: outtime,
            resourceId: row.resourceId
          }
        })
      } else {
        this.v_MyMessage(
          this.$t('alarm.alarmWarning.theTimeIsWrong'),
          'warning'
        )
      }
    },

    // 历史轨迹回放
    historicalTrackPlayBack(index, row) {
      console.log(row)
      const self = this
      // 轨迹回放元素
      var objValue = row.resourceId
      // 开始时间
      var startTime = new Date(row.intime).getTime() - 1000 * 60
      // 结束时间
      var endTime = new Date(row.outTime).getTime() + 1000 * 60
      if (endTime - startTime > 1000 * 60 * 60 * 2) {
        endTime = startTime + 1000 * 60 * 60 * 2
      }
      this.param = {
        // "departmentId": parseInt(this.deptValue),
        resourceId: objValue,
        startTime: self.v_FormatDateTime(startTime),
        endTime: self.v_FormatDateTime(endTime),
        mapId: row.layerId
      }
      console.log(this.param)
      this.currentMapId = row.layerId + ''
      this.showDetail = !this.showDetail
      // this.progressIndex = 0;
    },

    closeDialog2() {
      clearTimeout(this.timeoutIndex)
    },

    // 显示告警位置
    handlePosition(index, row) {
      this.positionDialogVisible = true
      // this.mapId = row.layerId;
      this.rowData = row
    },

    // 显示位置Dialog打开动画结束后的回调
    openPosiotionDialogCallBack() {
      const self = this
      // 根据地图中的层号获取地图参数
      getMap(parseInt(self.rowData.layerId)).then((res) => {
        const RES = this.responseUse(res)
        // 初始化地图
        Load_Map(
          baseUrl + RES.mapPath,
          RES.mapActualX,
          RES.mapActualY,
          RES.mapPixelX,
          RES.mapPixelY,
          RES.mapPixelX / RES.mapActualX,
          [RES.mapOriginX, RES.mapOriginY]
        )
        // 初始化容器
        self.initSource()
        // 添加位置点到地图中去
        const point = new Point(
          _TransPixel([self.rowData.posX, self.rowData.posY])
        )
        const feature = new Feature(point)
        self.alarmSource.addFeature(feature)

        // 设置当前标签的位置居中显示
        setMapCenter(_TransPixel([self.rowData.posX, self.rowData.posY]))
      })
    },

    closePositionDialogCallBack() {
      this.releaseSource()
      _iMap.removeLayer(this.alarmLayer)
      this.alarmSource = null
      this.alarmLayer = null
    },

    // 初始化位置容器
    initSource() {
      this.alarmSource = new Vector({
        wrapX: false
      })

      this.alarmLayer = new VectorLayer({
        minResolution: 0,
        maxResolution: _dPR * 2.4,
        source: this.alarmSource,
        zIndex: 10000,
        renderBuffer: 100,
        updateWhileAnimating: true,
        updateWhileInteracting: true,
        style: function(feature, resolution) {
          return TagStyle(feature, resolution, -9999)
        }
      })

      _iMap.addLayer(this.alarmLayer)
    },

    // 释放地图中的资源
    releaseSource() {
      if (this.alarmSource != null) {
        const oldFeatures = this.alarmSource.getFeatures() // 现在已有的标签数据
        let len = oldFeatures.length
        while (len > 0) {
          len--
          this.alarmSource.removeFeature(oldFeatures[len])
          oldFeatures.splice(len, 1)
        }
      }
    },

    handleChange(val) {
      this.multipleSelection = val
      // this.single = val.length !== 1
      this.multiple = !val.length
    },
    // 搜索
    searchData() {
      this.initB = true
      // this.cur_page = 1
      this.queryParams.pageNum = 1
      this.initAlarmlist()
    },

    // 刷新窗口
    windowRefresh: function() {
      this.tableMaxHeight = window.innerHeight - 240
    },
    // 详情dialog打开动画结束时的回调
    openDialogCallBack() {
      const self = this
      setTimeout(() => {
        // 请求轨迹点数据
        self.loadMapAndTrack()
      }, 1000)
    },
    /**
     * 关闭dialog时的回调函数
     */
    closeDialog() {
      this.clearMap()
      clearTimeout(this.timeoutIndex)

      if ($('.playbtn i').attr('class') === 'al-icon-carpause') {
        $('.playbtn i').attr('class', 'al-icon-carplay')
        this.playbtnTooltip = '播放'
      }
      this.trackData = []
      this.progressIndex = 0
      this.progressLimitIndex = 0
    },
    // 播放按钮响应
    clickPlayBtn() {
      clearTimeout(this.timeoutIndex)
      const className = $('.playbtn i').attr('class')

      if (className === 'al-icon-carplay') {
        // 处于暂定状态
        $('.playbtn i').attr('class', 'al-icon-carpause')
        this.playbtnTooltip = '暂停'
        // 播放
        this.drawLine()
      } else if (className === 'al-icon-carpause') {
        // 处于播放状态
        $('.playbtn i').attr('class', 'al-icon-carplay')
        this.playbtnTooltip = '播放'
        // 暂停
      }
    },
    // 绘制线
    drawLine() {
      let lineFeature
      let to
      let markPoint
      let markFeature
      const from = [
        this.trackData[this.progressIndex].posX,
        this.trackData[this.progressIndex].posY
      ]
      if (this.progressIndex === this.trackData.length - 1) {
        to = from
        $('#Tagtime').text(this.trackData[this.progressIndex].speed)
      } else {
        const toIndex = this.progressIndex + 1
        to = [this.trackData[toIndex].posX, this.trackData[toIndex].posY]
        $('#Tagtime').text(this.trackData[toIndex].speed)
      }

      // 画点
      const coords = [_TransPixel(from), _TransPixel(to)]
      if (this.progressIndex === 0) {
        const first = [this.trackData[0].posX, this.trackData[0].posY]
        markPoint = new Point(_TransPixel(first))
      } else {
        // alert(this.progressIndex)
        markPoint = new Point(_TransPixel(to))
      }
      markFeature = new Feature(markPoint)
      // 画线
      lineFeature = new Feature(new LineString(coords))
      lineFeature.setStyle(this.styles.linestring)
      this.lineSource.addFeature(lineFeature)

      // 定时划线到地图中去
      if (this.progressIndex < this.trackData.length - 1) {
        const self = this
        this.progressIndex++
        let temp
        if (self.speedIndex === 0) {
          temp = 300 * 2
        } else {
          temp = (300 / self.speedIndex).toFixed()
        }
        if (this.progressIndex < this.progressLimitIndex) {
          self.drawLine()
        } else {
          self.timeoutIndex = setTimeout(function() {
            self.drawLine()
          }, temp)
        }
      }

      const toObj = this.lineSource.getFeatureById('to')

      if (toObj != null) {
        // 已经添加过
        toObj.getGeometry().setCoordinates(_TransPixel(to))
      } else {
        markFeature.setId('to')
        markFeature.setStyle(this.styles.geoMarker)
        this.lineSource.addFeature(markFeature)
      }
    },
    // 进度条发生变化时的回调函数
    progressValueChange(val) {
      this.progressIndex = 0
      this.progressLimitIndex = parseInt(val)

      clearTimeout(this.timeoutIndex)
      this.clearMap()
      this.drawLine()
    },
    // 清除地图中的数据
    clearMap() {
      if (this.lineSource != null) {
        const self = this
        self.lineSource.forEachFeature(function(feature) {
          self.lineSource.removeFeature(feature)
        })
        // _iMap.removeLayer(self.lineLayer);
      }
    },
    // 请求历史轨迹详情数据，加载地图，渲染轨迹
    loadMapAndTrack() {
      const self = this
      self.progressIndex = 0 // 防止没有查到数据时，无法置零
      if (!self.currentMapId) {
        return
      }

      if (self.currentMapId) {
        getMap(self.currentMapId).then((res) => {
          const RES = self.responseUse(res)
          if (undefined != RES) {
            Load_Map(
              baseUrl + RES.mapPath,
              RES.mapActualX,
              RES.mapActualY,
              RES.mapPixelX,
              RES.mapPixelY,
              RES.mapPixelX / RES.mapActualX,
              [RES.mapOriginX, RES.mapOriginY]
            )

            getHistoryInfoDetail(self.param).then((res) => {
              const RES = self.responseUse(res)
              if (undefined != RES) {
                if (RES.length > 0) {
                  self.trackData = RES

                  if (self.trackData.length > 1) {
                    self.progressMax = self.trackData.length - 1
                  } else {
                    self.progressMax = 1
                  }
                  console.log(
                    '索引：',
                    self.progressIndex,
                    '最大值：',
                    self.progressMax
                  )

                  self.initData()

                  if ($('.playbtn i').attr('class') === 'al-icon-carplay') {
                    // 处于暂定状态
                    $('.playbtn i').attr('class', 'al-icon-carpause')
                    self.playbtnTooltip = '暂停'
                  }
                } else {
                  self.v_MyMessage(self.$t('Notice.noTrackDetails'), 'warning')
                }
              }
            })
          }
        })
      }
    },
    // 格式化进度滑块中的tooltip中的文字
    formatProgressTooltip(val) {
      // if (this.trackData[val].speed) {
      //   return this.trackData[val].speed;
      // }
      // return '';
    },
    // 往地图容器
    initData: function() {
      // 移除标签层信息
      _iMap.removeLayer(this.lineLayer)
      // 每次进入不管是否切换查看的详情数据
      // 都将地图中的数据清空

      if (this.lineSource == null) {
        this.lineSource = new Vector({
          wrapX: false
        })
      }

      if (this.lineLayer == null) {
        this.lineLayer = new VectorLayer({
          minResolution: 0,
          maxResolution: _dPR * 2.4,
          source: this.lineSource,
          zIndex: 10000,
          renderBuffer: 100,
          updateWhileAnimating: true,
          updateWhileInteracting: true,
          style: function(feature, resolution) {
            return TagStyle(feature, resolution)
          }
        })
      }

      _iMap.addLayer(this.lineLayer)

      // 往地图中加载轨迹数据
      this.progressIndex = 0
      this.drawLine()
    },

    handleVideoMp4: function(index, row) {
      this.videoDialogVisible = !this.videoDialogVisible
      var src =
        'http://' +
        window.g.IP +
        ':' +
        window.g.servicePort +
        JSON.parse(row.recordUrlList)[0].snapUrl
      $('#videoPlace').html(
        '<video id="videPlay" width="420" style="margin-top:15px;" controls="controls"><source src=' +
          src +
          ' type="video/mp4" /></video>'
      )
    }
  }
}
</script>

<style scoped>
#body {
  width: 100%;
  height: 100%;
}

.handle-box {
  /* background-color: #939e89; */
  /* padding: 10px; */
  /* margin-bottom: 10px; */
  min-width: 1140px;
}
.handle-box span {
  margin-right: 10px;
  color: #666666;
}

span {
  font-size: 13px;
}

.datalist {
  /* width: 100%; */
  min-width: 1100px;
}

/* 当前点时间显示控件 */
.historytime {
  position: absolute;
  bottom: 40px;
  left: 150px;
  display: none;
}
.toolrow {
  position: absolute;
  width: 800px;
  height: 40px;
  bottom: 40px;
  left: 50%;
  margin-left: -400px !important;
  /* background-color: brown; */
}

.toolrow .el-col {
  line-height: 40px;
}

/* 播放进度条 */
.progress_slider {
  /* position: absolute; */
  width: 500px;
  /* left: 250px;
  bottom: 30px; */
}

/* 速度进度条 */
.speed_slider {
  /* position: absolute; */
  width: 200px;
  /* left: 830px;
  bottom: 35px; */
}
.speed_slider span {
  color: #409eff;
  font-size: 16px;
}
#mapbox3 {
  background-color: #fff;
  /*z-index: 10000;*/
}

.el-table .background-green {
  background: green;
}

.el-table .background-red {
  background: red;
}

.el-table .background-pink {
  background: pink;
}
.fontsize{
  font-size: 20px;
}
</style>
